package com.atguigu.yygh.order.service.impl;


import com.alibaba.fastjson.JSONObject;
import com.atguigu.yygh.common.exception.YYGHException;
import com.atguigu.yygh.enums.OrderStatusEnum;
import com.atguigu.yygh.enums.PaymentStatusEnum;
import com.atguigu.yygh.hosp.client.HospitalFeignClient;
import com.atguigu.yygh.model.order.OrderInfo;
import com.atguigu.yygh.model.order.PaymentInfo;
import com.atguigu.yygh.model.user.Patient;
import com.atguigu.yygh.mq.MqConst;
import com.atguigu.yygh.mq.RabbitService;
import com.atguigu.yygh.order.mapper.OrderInfoMapper;
import com.atguigu.yygh.order.service.OrderInfoService;
import com.atguigu.yygh.order.service.PaymentService;
import com.atguigu.yygh.order.service.WeixinService;
import com.atguigu.yygh.order.utils.HttpRequestHelper;
import com.atguigu.yygh.user.client.UserFeignClient;
import com.atguigu.yygh.vo.hosp.ScheduleOrderVo;
import com.atguigu.yygh.vo.msm.MsmVo;
import com.atguigu.yygh.vo.order.OrderCountQueryVo;
import com.atguigu.yygh.vo.order.OrderCountVo;
import com.atguigu.yygh.vo.order.OrderMqVo;
import com.atguigu.yygh.vo.order.OrderQueryVo;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import net.sf.jsqlparser.expression.DateTimeLiteralExpression;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * <p>
 * 订单表 服务实现类
 * </p>
 *
 * @author atguigu
 * @since 2022-03-16
 */
@Service
public class OrderInfoServiceImpl extends ServiceImpl<OrderInfoMapper, OrderInfo> implements OrderInfoService {


    @Autowired
    private HospitalFeignClient hospitalFeignClient;
    @Autowired
    private UserFeignClient userFeignClient;
    @Autowired
    private RabbitService rabbitService;
    @Autowired
    private WeixinService weixinService;
    @Autowired
    private PaymentService paymentService;


    @Override
    public Long submitOrder(String scheduleId, Long patientId) {
        //1.根据排班id获取排班信息
        ScheduleOrderVo schedule = hospitalFeignClient.getScheduleById(scheduleId);
        //2.根据就诊人id获取就诊人信息
        Patient patient = userFeignClient.getPatientById(patientId);
        //3.平台系统请求第三方医院系统，确认是否能够挂号

        Map<String, Object> paramMap = new HashMap<>();

        paramMap.put("hoscode",schedule.getHoscode());
        paramMap.put("depcode",schedule.getDepcode());
        paramMap.put("hosScheduleId",schedule.getHosScheduleId());
        paramMap.put("reserveDate",new DateTime(schedule.getReserveDate()).toString("yyyy-MM-dd"));
        paramMap.put("reserveTime", schedule.getReserveTime());
        paramMap.put("amount",schedule.getAmount()); //挂号费用

        paramMap.put("name", patient.getName());
        paramMap.put("certificatesType",patient.getCertificatesType());
        paramMap.put("certificatesNo", patient.getCertificatesNo());
        paramMap.put("sex",patient.getSex());
        paramMap.put("birthdate", patient.getBirthdate());
        paramMap.put("phone",patient.getPhone());
        paramMap.put("isMarry", patient.getIsMarry());
        paramMap.put("provinceCode",patient.getProvinceCode());
        paramMap.put("cityCode", patient.getCityCode());
        paramMap.put("districtCode",patient.getDistrictCode());
        paramMap.put("address",patient.getAddress());

        //联系人
        paramMap.put("contactsName",patient.getContactsName());
        paramMap.put("contactsCertificatesType", patient.getContactsCertificatesType());
        paramMap.put("contactsCertificatesNo",patient.getContactsCertificatesNo());
        paramMap.put("contactsPhone",patient.getContactsPhone());
        paramMap.put("timestamp", HttpRequestHelper.getTimestamp());
        //String sign = HttpRequestHelper.getSign(paramMap, signInfoVo.getSignKey());
        paramMap.put("sign", "");

        JSONObject jsonObject = HttpRequestHelper.sendRequest(paramMap, "http://localhost:9998/order/submitOrder");
       // 3.2.1 可以就将上述三部分内容插入到order_info表中
        if(jsonObject != null && jsonObject.getIntValue("code") == 200){

            OrderInfo orderInfo = new OrderInfo();
            orderInfo.setUserId(patient.getUserId());
            //服务器生成的一个唯一标识
            String outTradeNo = System.currentTimeMillis() + ""+ new Random().nextInt(100);
            orderInfo.setOutTradeNo(outTradeNo);
            orderInfo.setHoscode(schedule.getHoscode());
            orderInfo.setHosname(schedule.getHosname());
            orderInfo.setDepcode(schedule.getDepcode());
            orderInfo.setDepname(schedule.getDepname());
            orderInfo.setTitle(schedule.getTitle());
            orderInfo.setScheduleId(schedule.getHosScheduleId());
            orderInfo.setReserveDate(schedule.getReserveDate());
            orderInfo.setReserveTime(schedule.getReserveTime());
            orderInfo.setPatientId(patientId);
            orderInfo.setPatientName(patient.getName());
            orderInfo.setPatientPhone(patient.getPhone());

            JSONObject data = jsonObject.getJSONObject("data");

            //预约记录唯一标识（医院预约记录主键）
            String hosRecordId = data.getString("hosRecordId");
            //预约序号
            Integer number = data.getInteger("number");;
            //取号时间
            String fetchTime = data.getString("fetchTime");;
            //取号地址
            String fetchAddress = data.getString("fetchAddress");;

            //设置添加数据--医院接口返回数据
            orderInfo.setHosRecordId(hosRecordId);
            orderInfo.setNumber(number);
            orderInfo.setFetchTime(fetchTime);
            orderInfo.setFetchAddress(fetchAddress);
            orderInfo.setAmount(schedule.getAmount());
            orderInfo.setQuitTime(schedule.getQuitTime());
            orderInfo.setOrderStatus(OrderStatusEnum.UNPAID.getStatus());



            baseMapper.insert(orderInfo);

            // 3.2.2 更新平台的可预约数和剩余可预约数的值
            Integer reservedNumber = data.getInteger("reservedNumber");
            Integer availableNumber = data.getInteger("availableNumber");

            OrderMqVo orderMqVo=new OrderMqVo();
            orderMqVo.setReservedNumber(reservedNumber);
            orderMqVo.setAvailableNumber(availableNumber);
            orderMqVo.setScheduleId(scheduleId);
            MsmVo msmVo=new MsmVo();
            msmVo.setPhone(patient.getPhone());
            msmVo.setTemplateCode("您预约的时间是：${time}，${when}该验证码5分钟内有效，请勿泄漏于他人！");
            Map<String,Object> map = new HashMap<String,Object>();
            map.put("time",schedule.getReserveDate());
            map.put("when",schedule.getReserveTime()==1?"下午":"上午");
            msmVo.setParam(map);
            orderMqVo.setMsmVo(msmVo);

            //您预约的 time 上午yyy点的牙科的xx 医生的:

            rabbitService.sendMessage(MqConst.EXCHANGE_DIRECT_ORDER,MqConst.ROUTING_ORDER,orderMqVo);


           // rabbitService.sendMessage(MqConst.EXCHANGE_DIRECT_ORDER,MqConst.ROUTING_ORDER,"海慧寺");
            //3.2.3  给就诊人信息,提醒预约成功！


            return orderInfo.getId();
        }else{
            //3.1 不可以： 抛出异常
            throw new YYGHException(20001,"挂号失败");
        }



    }

    @Override
    public Page<OrderInfo> getOrdersByQueryCondition(Integer pageNum, Integer pageSize, OrderQueryVo orderQueryVo) {

        Page<OrderInfo> page = new Page<OrderInfo>(pageNum,pageSize);


        //orderQueryVo获取条件值
        String name = orderQueryVo.getKeyword(); //医院名称
        Long patientId = orderQueryVo.getPatientId(); //就诊人名称
        String orderStatus = orderQueryVo.getOrderStatus(); //订单状态
        String reserveDate = orderQueryVo.getReserveDate();//安排时间
        String createTimeBegin = orderQueryVo.getCreateTimeBegin();
        String createTimeEnd = orderQueryVo.getCreateTimeEnd();
        //对条件值进行非空判断
        QueryWrapper<OrderInfo> wrapper = new QueryWrapper<>();

        //TODO: 判断当前用户id非空，使用用户id查询  !!!

        if(!StringUtils.isEmpty(name)) {
            wrapper.like("hosname",name);
        }
        if(!StringUtils.isEmpty(patientId)) {
            wrapper.eq("patient_id",patientId);
        }
        if(!StringUtils.isEmpty(orderStatus)) {
            wrapper.eq("order_status",orderStatus);
        }
        if(!StringUtils.isEmpty(reserveDate)) {
            wrapper.ge("reserve_date",reserveDate);
        }
        if(!StringUtils.isEmpty(createTimeBegin)) {
            wrapper.ge("create_time",createTimeBegin);
        }
        if(!StringUtils.isEmpty(createTimeEnd)) {
            wrapper.le("create_time",createTimeEnd);
        }

        wrapper.eq("user_id",orderQueryVo.getUserId());

        Page<OrderInfo> orderInfoPage = baseMapper.selectPage(page, wrapper);
        orderInfoPage.getRecords().parallelStream().forEach(item->{
            this.packageOrderInfo(item);
        });
        return orderInfoPage;
    }

    @Override
    public OrderInfo getOrderDetail(Long orderId) {
        OrderInfo orderInfo = baseMapper.selectById(orderId);
        this.packageOrderInfo(orderInfo);
        return orderInfo;
    }

    @Override
    public void cancelOrder(Long orderId) {
        //1.首先要查看当前时间是否已经超过了当前订单所规定的退号时间,如果超过了，抛出异常，不让取消
        OrderInfo orderInfo = baseMapper.selectById(orderId);
        Date quitTime = orderInfo.getQuitTime();
        DateTime dateTime = new DateTime(quitTime);
        if(dateTime.isBeforeNow()){
            throw new YYGHException(20001,"已经超过规定的退号时间");
        }

        //只有在已支付的情况下才完成退款
        if(orderInfo.getOrderStatus()==OrderStatusEnum.PAID.getStatus()){
           boolean flag= weixinService.refund(orderId);
           if(!flag){
               throw new YYGHException(20001,"退款失败");
           }
        }
        orderInfo.setOrderStatus(OrderStatusEnum.CANCLE.getStatus());
        baseMapper.updateById(orderInfo);

      //2.3 更新订单状态及支付记录表的支付状态

        QueryWrapper<PaymentInfo> paymentInfoQueryWrapper=new QueryWrapper<PaymentInfo>();
        paymentInfoQueryWrapper.eq("order_id", orderId);
        PaymentInfo one = paymentService.getOne(paymentInfoQueryWrapper);
        one.setPaymentStatus(PaymentStatusEnum.REFUND.getStatus());
        paymentService.updateById(one);
        //2.4 更新排班数据
        //发送mq信息更新预约数 我们与下单成功更新预约数使用相同的mq信息，不设置可预约数与剩余预约数，接收端可预约数减1即可

        OrderMqVo orderMqVo = new OrderMqVo();
        orderMqVo.setScheduleId(orderInfo.getScheduleId());
        //短信提示
        MsmVo msmVo = new MsmVo();
        msmVo.setPhone(orderInfo.getPatientPhone());
        orderMqVo.setMsmVo(msmVo);
        rabbitService.sendMessage(MqConst.EXCHANGE_DIRECT_ORDER, MqConst.ROUTING_ORDER, orderMqVo);


        //2.6.通知第三方医院
        Map<String,Object> paramMap=new HashMap<String,Object>();
        paramMap.put("hosRecordId",orderInfo.getHosRecordId());

        JSONObject jsonObject = HttpRequestHelper.sendRequest(paramMap, "http://localhost:9998/order/updateCancelStatus");
    }

    @Override
    public void patientTips() {
        QueryWrapper<OrderInfo> queryWrapper=new QueryWrapper<OrderInfo>();
        queryWrapper.eq("reserve_date",new DateTime().toString("yyyy-MM-dd"));
        queryWrapper.ne("order_status",OrderStatusEnum.CANCLE.getStatus());
        List<OrderInfo> orderInfos = baseMapper.selectList(queryWrapper);
        for (OrderInfo orderInfo : orderInfos) {
            MsmVo msmVo=new MsmVo();
            msmVo.setPhone(orderInfo.getPatientPhone());
            String reserveDate = new DateTime(orderInfo.getReserveDate()).toString("yyyy-MM-dd") + (orderInfo.getReserveTime()==0 ? "上午": "下午");
            Map<String,Object> param = new HashMap<String,Object>(){{
                put("title", orderInfo.getHosname()+"|"+orderInfo.getDepname()+"|"+orderInfo.getTitle());
                put("reserveDate", reserveDate);
                put("name", orderInfo.getPatientName());
            }};
            msmVo.setParam(param);


            rabbitService.sendMessage(MqConst.EXCHANGE_DIRECT_SMS,MqConst.ROUTING_SMS_ITEM,msmVo);
        }
    }

    @Override
    public Map<String, Object> countOrderInfo(OrderCountQueryVo orderQueryVo) {
        Map<String,Object> map = new HashMap<String,Object> ();

        List<OrderCountVo> orderCountVos= baseMapper.countOrderInfo(orderQueryVo);

        List<String> dateList = orderCountVos.stream().map(item -> item.getReserveDate()).collect(Collectors.toList());
        List<Integer> countList = orderCountVos.stream().map(item -> item.getCount()).collect(Collectors.toList());
        map.put("dateList",dateList);
        map.put("countList",countList);
        return map;
    }


    private void packageOrderInfo(OrderInfo item) {
        item.getParam().put("orderStatusString",OrderStatusEnum.getStatusNameByStatus(item.getOrderStatus()));
    }
}
